package com.java.collection;

import java.util.Arrays;

/**
 * 基于数组实现一个阻塞式队列
 * 1)向容器放数据,满了则等待
 * 2)从容器取数据,空了则等待
 */
class SimpleArrayBlockQueue{
      private Object[] array;
      private int size;
      public SimpleArrayBlockQueue(int cap){
          array=new Object[cap];
      }
      //size位置放
      public synchronized void put(Object obj){
          //1.容器是否满了,满了要等待
          while(size==array.length)
            try{this.wait();}catch (Exception e){}
          //2.存储元素
          array[size]=obj;
          //3.有效元素个数加1
          size++;
          //4.通知消费者线程取数据
          this.notifyAll();
      }
      //下标为0的位置取
      public synchronized Object take(){
          //1.容器是否为空,空了则等待
          while(size==0)
              try{this.wait();}catch (Exception e){}
          //2.取元素
          Object temp=array[0];
          System.arraycopy(array,1,array,0,size-1);
          array[size-1]=null;
          //3.有效元素个数减1
          size--;
          //4.通知生产者线程放数据
          this.notifyAll();
          return temp;
      }

    @Override
    public String toString() {
        return "SimpleArrayBlockQueue{" +
                "array=" + Arrays.toString(array) +
                '}';
    }
}
public class SimpleArrayBlockQueueTests {
    public static void main(String[] args) {
        SimpleArrayBlockQueue blockQueue=new SimpleArrayBlockQueue(3);
        blockQueue.put("A");
        blockQueue.put("B");
        blockQueue.put("C");
        System.out.println(blockQueue);
        blockQueue.take();
        blockQueue.take();
        blockQueue.take();
        System.out.println(blockQueue);
        blockQueue.take();
        System.out.println(blockQueue);
    }
}
